package BLC

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"strconv"
	"time"
)

type Block struct {
	//1.区块高度
	Height int64
	//2.上一个区块的hash
	PrevBlockHash []byte
	//3.交易数据
	Data []byte
	//4.时间戳
	Timestamp int64
	//5.Hash
	Hash []byte
}

func (block *Block) SetHash() {
	// 1. Height

	heightBytes := IntToHex(block.Height)
	fmt.Println(heightBytes)

	//2 时间戳,先转成二进制在转成数组

	timeString := strconv.FormatInt(block.Timestamp, 2)
	fmt.Println(timeString)
	timeBytes := []byte(timeString)
	fmt.Println(timeBytes)

	//timeBytes = IntToHex(block.Timestamp)
	//fmt.Println(timeBytes)

	//3 拼接所有属性
	blockBytes := bytes.Join([][]byte{heightBytes,block.PrevBlockHash,block.Data,timeBytes},[]byte{})
	fmt.Println(blockBytes)

	//4 生成hash
	hash := sha256.Sum256(blockBytes)
	block.Hash = hash[:]

}

//1. 创建新的区块
func NewBlock(data string, height int64, PrevBlockHash []byte) *Block {
	// 1 创建区块
	block := &Block{height, PrevBlockHash, []byte(data),
		time.Now().Unix(), nil}

	// 设置hash
	block.SetHash()

	return block

}
